<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>
        {% block title %}
        {% endblock %}
    </title>
    <link href="/static/bootstrap-3.4.1/css/bootstrap.css" rel="stylesheet">

    <!--样式-->
    <style>
        .bth_com_container {
            display: flex;
            /* 弹性布局 */
            justify-content: center;
            /* 子元素水平居中 */
            gap: 10px;
            /* 间距控制 */
            margin-bottom: 10px;
        }

        .btn_com_link {
            background-color: green;
        }

        /* 刷新按钮动画样式 */
        #refresh-ports.refreshing {
            background-color: #f0ad4e;
            border-color: #eea236;
        }

        /* 旋转动画 */
        .glyphicon-spin {
            -webkit-animation: spin 1s infinite linear;
            -moz-animation: spin 1s infinite linear;
            -o-animation: spin 1s infinite linear;
            animation: spin 1s infinite linear;
        }

        @-moz-keyframes spin {
            0% {
                -moz-transform: rotate(0deg);
            }

            100% {
                -moz-transform: rotate(360deg);
            }
        }

        @-webkit-keyframes spin {
            0% {
                -webkit-transform: rotate(0deg);
            }

            100% {
                -webkit-transform: rotate(360deg);
            }
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        /* 通知样式 */
        .notification-container {
            position: fixed;
            top: 80px;
            right: 20px;
            z-index: 1050;
            max-width: 300px;
        }

        .notification {
            margin-bottom: 10px;
            padding: 15px;
            border-radius: 4px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            animation: slideInRight 0.3s ease-out;
        }

        .notification.success {
            background-color: #dff0d8;
            border: 1px solid #d6e9c6;
            color: #3c763d;
        }

        .notification.error {
            background-color: #f2dede;
            border: 1px solid #ebccd1;
            color: #a94442;
        }

        .notification.info {
            background-color: #d9edf7;
            border: 1px solid #bce8f1;
            color: #31708f;
        }

        .status-text {
            font-weight: 600;
            font-size: 1.1em;
        }

        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-connected {
            background-color: #5cb85c;
            box-shadow: 0 0 5px #5cb85c;
        }

        .status-disconnected {
            background-color: #d9534f;
        }

        .heartbeat-info {
            color: #7f8c8d;
            font-size: 0.9em;
            margin-left: 10px;
        }


        @keyframes slideInRight {
            from {
                transform: translateX(100%);
                opacity: 0;
            }

            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
    </style>

</head>

<body>

    <!--导航栏-->
    <nav class="navbar navbar-default" style="border-radius: 0">
        <div class="container">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button aria-expanded="false" class="navbar-toggle collapsed"
                    data-target="#bs-example-navbar-collapse-1" data-toggle="collapse" type="button">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">元器件存取库</a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">

                <ul class="nav navbar-nav">
                    <li><a href="#">BOM配单</a></li>
                    <li><a href="/order/stock">库存</a></li>
                    <li class="dropdown">
                        <a aria-expanded="false" aria-haspopup="true" class="dropdown-toggle" data-toggle="dropdown"
                            href="#" role="button">Dropdown <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Action</a></li>
                            <li><a href="#">Another action</a></li>
                            <li><a href="#">Something else here</a></li>
                            <li class="divider" role="separator"></li>
                            <li><a href="#">Separated link</a></li>
                            <li class="divider" role="separator"></li>
                            <li><a href="#">One more separated link</a></li>
                        </ul>
                    </li>
                </ul>


                <ul class="nav navbar-nav navbar-right">
                    <!-- 串口连接状态显示 -->

                    <li><a href="#" id="com_link_pop">
                            <span class="glyphicon glyphicon-retweet" id="connection-icon" style="color: gray;"></span>
                        </a>
                    </li>
                    <li class="dropdown">
                        <!-- 获取用户名 -->
                        <a aria-expanded="false" aria-haspopup="true" class="dropdown-toggle" data-toggle="dropdown"
                            href="#" role="button">{{get_real_name()}} <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Action</a></li>
                            <li><a href="#">Another action</a></li>
                            <li><a href="#">Something else here</a></li>
                            <li class="divider" role="separator"></li>
                            <li><a href="#">Separated link</a></li>
                        </ul>
                    </li>
                </ul>
            </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
    </nav>
    <!--内容-->
    <div class="container">
        {%block body%}
        {%endblock%}
    </div>

    <!-- 串口连接弹窗 -->
    <div aria-labelledby="comModalLabel" class="modal fade" id="com_set" role="dialog" tabindex="-1">


        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button aria-label="Close" class="close" data-dismiss="modal" type="button"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="comModalLabel">串口连接设置</h4>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="form-group">
                            <label for="port-select">选择串口:</label>
                            <select id="port-select">
                                <option value="">请选择串口</option>
                                <option value="COM1">COM1 - ELTIMA Virtual Serial Port (COM1-&gt;COM2)</option>
                                <option value="COM2">COM2 - ELTIMA Virtual Serial Port (COM2-&gt;COM1)</option>
                                <option value="COM6">COM6 - JLVirtualJtagSerial Device (COM6)</option>
                            </select>
                            <button class="btn btn-default" id="refresh-ports">
                                <span aria-hidden="true" class="glyphicon glyphicon-refresh"></span>
                                刷新串口列表
                            </button>
                        </div>
                        <div class="form-group">
                            <label for="baud-rate">波特率:</label>
                            <select id="baud-rate">
                                <option value="9600">9600</option>
                                <option value="19200">19200</option>
                                <option value="38400">38400</option>
                                <option value="57600">57600</option>
                                <option value="115200">115200</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="bth_com_container">
                    <button class="btn_com_link" id="connect-btn" style="width: 20%; color:white;">连接串口</button>
                    <button id="disconnect-btn" style="width: 20%;">断开连接</button>
                </div>

            </div>
        </div>
    </div>

    <!-- 定义客户端脚本 -->
    <script>
        // 全局变量
        let isConnected = false;//串口连接标志位
        let currentPort = '';
        let currentBaud = '9600';
        let dataFormat = 'text'; //数据格式 text 或 hex
        let dataUpdateInterval = null;

        // 页面加载时自动运行find_serial_ports函数
        document.addEventListener('DOMContentLoaded', function () {
            console.log("页面加载完成.");
            const baudRate = document.getElementById('baud-rate');//波特率

            window.baudRate = baudRate;//波特率

            // 初始化按钮变量
            window.connectBtn = document.getElementById('connect-btn');//连接按钮
            window.disconnectBtn = document.getElementById('disconnect-btn');//断开连接按钮

            // 页面加载后自动获取并更新串口连接状态
            updateStatus();

            // 启动定时检查状态更新（每秒检查一次）
            dataUpdateInterval = setInterval(updateStatus, 300);

            // 连接串口图标被点击
            document.getElementById('com_link_pop').addEventListener('click', function () {
                document.getElementById('refresh-ports').addEventListener('click', refreshBtn_event);//刷新串口列表按钮
                document.getElementById('connect-btn').addEventListener('click', connectBtn_event);//连接按钮
                document.getElementById('disconnect-btn').addEventListener('click', disconnectBtn_event);//断开连接按钮
                console.log("弹出串口连接设置界面");

                // 弹出串口连接设置界面
                $('#com_set').modal('show');
            });
        });

        // 加载串口列表函数
        async function loadSerialPorts() {
            try {
                console.log("正在调用find_serial_ports函数...");
                const response = await fetch('/api/ports');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const ports = await response.json();
                console.log("获取到的串口列表:", ports);

                // 更新串口选择下拉框
                updatePortSelect(ports);

            } catch (error) {
                console.error('加载串口列表失败:', error);
                // 显示错误信息
                showNotification('加载串口列表失败: ' + error.message, 'error');
            }
        }

        // 更新串口选择下拉框
        function updatePortSelect(ports) {
            const portSelect = document.getElementById('port-select');
            window.portSelect = portSelect;

            if (!portSelect) {
                console.error('找不到串口选择下拉框元素');
                return;
            }

            // 清空现有选项（保留第一个"请选择串口"选项）
            while (portSelect.options.length > 1) {
                portSelect.remove(1);
            }

            // 添加新的串口选项
            ports.forEach(port => {
                const option = document.createElement('option');
                option.value = port.device;
                option.textContent = `${port.device} - ${port.description}`;
                portSelect.appendChild(option);
            });

            console.log(`已更新串口列表，共找到 ${ports.length} 个可用串口`);
            showNotification(`已加载 ${ports.length} 个可用串口`, 'success');
        }

        // 显示通知函数
        function showNotification(message, type = 'info') {
            // 简单的控制台通知
            console.log(`[${type.toUpperCase()}] ${message}`);

            // 可以在这里添加更复杂的UI通知，比如使用Bootstrap的alert
            // 例如：$('.alert-container').append(`<div class="alert alert-${type}">${message}</div>`);
        }

        // 显示模态框通知函数
        function showModalNotification(message, type = 'info') {
            // 确保通知容器存在
            let container = document.querySelector('.notification-container');
            if (!container) {
                container = document.createElement('div');
                container.className = 'notification-container';
                document.body.appendChild(container);
            }

            // 创建通知元素
            const notification = document.createElement('div');
            notification.className = `notification ${type}`;
            notification.innerHTML = `
                <strong>${type === 'success' ? '✓' : type === 'error' ? '✗' : 'ℹ'}</strong>
                ${message}
            `;

            // 添加到容器
            container.appendChild(notification);

            // 3秒后自动移除
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.style.opacity = '0';
                    notification.style.transform = 'translateX(100%)';
                    setTimeout(() => {
                        if (notification.parentNode) {
                            notification.parentNode.removeChild(notification);
                        }
                    }, 300);
                }
            }, 3000);
        }

        // 刷新串口事件
        async function refreshBtn_event() {
            const refreshBtn = document.getElementById('refresh-ports');
            const originalText = refreshBtn.innerHTML;

            try {
                console.log("刷新串口列表...");

                // 禁用按钮并显示加载状态
                refreshBtn.disabled = true;
                refreshBtn.innerHTML = '<span class="glyphicon glyphicon-refresh glyphicon-spin"></span> 刷新中...';

                // 添加旋转动画效果
                refreshBtn.classList.add('refreshing');

                // 检查当前是否已连接，如果已连接则先断开
                if (isConnected) {
                    console.log("检测到当前串口已连接，先断开连接...");
                    await disconnectSerial();
                    showModalNotification('已断开当前串口连接', 'info');
                }

                // 调用加载函数
                await loadSerialPorts();

                // 恢复按钮状态
                refreshBtn.disabled = false;
                refreshBtn.innerHTML = originalText;
                refreshBtn.classList.remove('refreshing');

                // 显示成功提示
                showModalNotification('串口列表刷新成功！', 'success');

            } catch (error) {
                console.error('刷新串口列表失败:', error);

                // 恢复按钮状态
                refreshBtn.disabled = false;
                refreshBtn.innerHTML = originalText;
                refreshBtn.classList.remove('refreshing');

                // 显示错误提示
                showModalNotification('刷新串口列表失败: ' + error.message, 'error');
            }
        }

        // 更新连接状态 每300ms执行一次
        async function updateStatus() {
            try {
                const response = await fetch('/api/status');
                const status = await response.json();

                isConnected = status.connected;
                currentPort = status.port_name || '';
                currentBaud = status.baud_rate || '9600';

                const connectionIcon = document.getElementById('connection-icon');

                if (isConnected) {
                    // 连接成功时将图标颜色设为绿色
                    if (connectionIcon) {
                        connectionIcon.style.color = 'rgb(0, 200, 0)';
                    }

                    // if (window.connectBtn) window.connectBtn.disabled = true;
                    if (window.disconnectBtn) window.disconnectBtn.disabled = false;
                } else {
                    // 未连接时将图标颜色设为灰色
                    if (connectionIcon) {
                        connectionIcon.style.color = 'gray';
                    }

                    // if (window.connectBtn) window.connectBtn.disabled = false;
                    if (window.disconnectBtn) window.disconnectBtn.disabled = true;
                }

                // 更新波特率选择
                window.baudRate.value = currentBaud;
            } catch (error) {
                console.error('获取状态失败:', error);
            }
        }
        // 连接串口
        async function connectBtn_event() {
            // 检查是否已经连接
            if (isConnected) {
                showNotification(`串口已连接: ${currentPort} (${currentBaud} baud)`, 'info');
                showModalNotification('串口已连接！', 'success');
                return;
            }

            const port = window.portSelect.value;
            const baud = window.baudRate.value;

            if (!port) {
                showNotification('请选择串口', 'error');
                return;
            }

            try {
                console.log("连接串口按钮 点击");
                const response = await fetch('/api/connect', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        port: port,
                        baud: parseInt(baud)
                    })
                });
                const result = await response.json();

                if (result.success) {
                    isConnected = true;
                    currentPort = port;
                    currentBaud = baud;
                    updateStatus();
                    showNotification(result.message, 'success');
                    
                    // 连接成功后自动关闭模态框
                    $('#com_set').modal('hide');
                    
                    // 连接成功后显示模态通知
                    showModalNotification('串口连接成功！', 'success');
                } else {
                    showNotification(result.message, 'error');
                    showModalNotification('串口连接失败！', 'error');
                }

            } catch (error) {
                console.error('连接串口失败:', error);
                showNotification('连接串口失败', 'error');

            }
        }
        //断开串口连接
        async function disconnectBtn_event() {
            try {
                console.log("断开连接串口按钮 点击");
                // 调用disconnectSerial函数处理断开连接逻辑
                await disconnectSerial();
            } catch (error) {
                console.error('断开连接串口失败:', error);
                showNotification('断开连接串口失败', 'error');
            }
        }

        // 断开连接 
        async function disconnectSerial() {
            try {
                const response = await fetch('/api/disconnect', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });

                const result = await response.json();

                if (result.success) {
                    isConnected = false;
                    currentPort = '';
                    updateStatus();
                    showNotification(result.message, 'success');
                }
            } catch (error) {
                console.error('断开连接失败:', error);
                showNotification('断开连接失败', 'error');
            }
        }

        // 发送数据到串口
        async function sendSerialData(data, format = 'text') {
            try {
                const response = await fetch('/api/send', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message: data,
                        format: format
                    })
                });

                const result = await response.json();

                if (result.success) {
                    showNotification(result.message, 'success');
                    return true;
                } else {
                    showNotification(result.message, 'error');
                    return false;
                }
            } catch (error) {
                console.error('发送数据失败:', error);
                showNotification('发送数据失败: ' + error.message, 'error');
                return false;
            }
        }
    </script>
    <script src="/static/jquery-3.6.0.min.js"></script>
    <script src="/static/bootstrap-3.4.1/js/bootstrap.js"></script>
    {% block js %}
    {% endblock %}

</body>

</html>